class MediasController < ApplicationController
      before_filter :authenticate_member, :except => ['download']
      before_filter :authenticate_admin, :except => ['show', 'index', 'search', 'edit', 'destroy', 'update', 'download']
      
  # GET /medias
  # GET /medias.xml
  def index
    page = params[:page] || 1
    if params[:change_filtering]
      session[:user][:local_dl_only] = (params[:local_dl_only] ? true : false)
    end
    if(params[:category_id]) # medias dune categ
      @category = Category.find(params[:category_id])
      @subcategories = Category.find_all_by_category_id(@category.id, :order => "label ASC")
      #@medias = @category.medias.sort { |a,b| b.updated_at <=> a.updated_at }
      @medias = Media.paginate_by_category_id(@category.id, :conditions =>("local_path != \"\"" if session[:user][:local_dl_only]), :page => page, :order => 'updated_at DESC')
      @title = @category.label
      @active_tab = @category.id
      render :layout => 'medias_categories.html'
    elsif (params[:user_id]) # trésors d'un user
      @user = User.find(params[:user_id])
      #@medias = @user.medias
      @medias = Media.paginate_by_user_id(@user.id, :page => page, :order => 'updated_at DESC')
      @title = "Les trésors de #{@user.nickname}"
      @active_tab = @user.id
    else # vieux média
      #@medias = Media.find(:all, :order => 'updated_at DESC', :limit => 100)
      @medias = Media.paginate(:all, :page => page, :order => 'updated_at ASC', :limit => 100)
      @title = "Vieux médias"
    end
  end

  def search
    page = params[:page] || 1
    if(params[:keywords])
      @medias = Media.paginate(:all, :conditions => ['local_path IS NULL AND nom LIKE ?', "%#{params[:keywords]}%"], :page => page, :order => 'updated_at DESC')
      @local_medias = Media.find(:all, :conditions => ['local_path != "" AND nom LIKE ?', "%#{params[:keywords]}%"], :order => 'updated_at DESC') if page.to_i == 1
      @title = 'Résultats de la recherche: '+ (params[:keywords])
    end
  end
  
  # GET /medias/1
  # GET /medias/1.xml
  def show
    @media = Media.find(params[:id])
    if request.xml_http_request?
      render :partial => 'show_files', :layout => false
    else
      @comment = Comment.new(:media_id => @media.id)
      respond_to do |format|
        format.html # show.html.erb
        format.xml  { render :xml => @media }
      end
    end
  end

  # GET /medias/new
  # GET /medias/new.xml
  def new
    @media = Media.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @media }
    end
  end

  # GET /medias/1/edit
  def edit
    @media = Media.find(params[:id])
  end

  # POST /medias
  # POST /medias.xml
  def create
    @media = Media.new(params[:media])

    respond_to do |format|
      if @media.save
        flash[:notice] = 'Media was successfully created.'
        format.html { redirect_to(@media) }
        format.xml  { render :xml => @media, :status => :created, :location => @media }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @media.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /medias/1
  # PUT /medias/1.xml
  def update
    @media = Media.find(params[:id])
    if ((session[:user].rights >= MODERATOR_USER)||(session[:user].id == @media.user_id))
      params[:media][:img_src] = WebWrapper.wrap_url(params[:media][:url].strip) if (params[:media][:img_src].empty? && !params[:media][:url].empty?)
      respond_to do |format|
      if @media.update_attributes(params[:media])
        flash[:notice] = 'Media was successfully updated.'
        format.html { redirect_to(@media) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @media.errors, :status => :unprocessable_entity }
      end
    end
    else
      flash[:notice] = "Vous n'avez pas les droits nécessaires pour effectuer cette action!"
      render :action => "show"
    end
  end

  # DELETE /medias/1
  # DELETE /medias/1.xml
  def destroy
    @media = Media.find(params[:id])
    if ((session[:user].rights >=MODERATOR_USER)||(session[:user].id == @media.user_id))
      if(@media.local_path && !@media.local_path.strip.empty?)
        if(@media.nzb_id && Hellanzb.instance)
          nzb_details = Hellanzb.instance.get_nzb_details(@media.nzb_id)
          if(nzb_details)
            case (nzb_details['status'])
              when NZB_QUEUED
                Hellanzb.instance.dequeue(@media.nzb_id)
              when NZB_DOWNLOADING
                Hellanzb.instance.cancel
              when NZB_PROCESSING
                flash[:notice] = "Ce media est en cours de traitement, et ne peut être supprimé pour l'instant."
                render :action => "show"
                return
            end
          end
        end
        FileUtils.rm_rf(HELLA_LOCAL_DONE + '/' + @media.local_path)
        if(@media.fichier && !@media.fichier.strip.empty?)
          @media.local_path=nil
          @media.user_id=0
          @media.nzb_id = 0
          @media.dl_count = 0
          @media.score = 0
          @media.save
        else
          @media.comments.destroy_all
          @media.destroy
        end
      elsif (session[:user].rights >=MODERATOR_USER)
        @media.comments.destroy_all
        @media.destroy
      else
        flash[:notice] = "Vous n'avez pas les permissions nécessaires pour supprimer ce média!"
      end
      unless @ret=@media.category
        @ret='/'
      end
      respond_to do |format|
        format.html { redirect_to(category_medias_url(@ret)) }
        format.xml  { head :ok }
      end
    else
      flash[:notice] = "Vous n'avez pas les droits nécessaires pour effectuer cette action!"
      render :action => "show"
    end
  end

  #TODO  send_data generate_tgz('dir'), :filename => 'dir.tgz'
  def download
    hash_ip = Digest::SHA2.hexdigest('zwx'+request.remote_ip+'rev')
    if(User.find_by_ip(hash_ip))
      if(params[:id] && media = Media.find(params[:id]))
        if(params[:dlpath] && params[:dlpath].length > 0 && !params[:dlpath].include?(".."))
#          Ranges to ignore:
#          bytes=N-
#          bytes=N-M
#          Ranges to consider:
#          bytes=0-
#          bytes=0-N
#          bytes=-
#          bytes=-N
#          *no range header*
#          
          #à moins que ce soit un resume, on incremente le compteur
          unless request.headers['Range'] =~ /bytes=[1-9]+[0-9]*-[0-9]*/
            Media.increment_counter(:dl_count, media.id)
          end
          file_path = params[:dlpath].join("/")
          send_file "#{HELLA_LOCAL_DONE}/#{media.local_path}/#{file_path}", :x_sendfile => true
        else
          flash[:notice] = "Adresse incorrecte!"
          redirect_to :back
        end
      end
    else
      flash[:notice] = "Votre IP n'est pas autorisée !"
      redirect_to '/'
    end
  end
end
